import { defineStore } from 'pinia'
import type { UserInfo, UserState } from './helper'
import {removeToken} from '../auth/helper'
import { defaultSetting, getLocalState, setLocalState } from './helper'
import { useAuthStore } from '../auth'

export const useUserStore = defineStore('user-store', {
  state: (): UserState => getLocalState(),
  actions: {
    updateUserInfo(userInfo: Partial<UserInfo>) {
      this.userInfo = { ...this.userInfo, ...userInfo }
      this.recordState()
    },
    updateUsername(username:String){
      this.userInfo.username=username
      this.recordState()
    },
    resetUserInfo() {
      this.userInfo = { ...defaultSetting().userInfo }
      this.recordState()
    },

    islogin(){
      if(useAuthStore().token!=undefined){
        return true
      }else{
        return false
      }
    },

    login(userInfo:any){
      this.userInfo.phonenum=userInfo.phonenum
      this.userInfo.password=userInfo.password
      this.userInfo.userid=userInfo.userid
      this.userInfo.username=userInfo.username
      useAuthStore().setToken(userInfo.phonenum)
      console.log("Token",useAuthStore().token)
      this.recordState()
      return true
    },

    logout(){
      removeToken()
      this.userInfo=defaultSetting()
      this.recordState()
    },

    recordState() {
      setLocalState(this.$state)
    },
  },
})
